const db = require('../../models/index');
const DAO = require('../../dao/sql-option-dao');
const logger = require('../../utils/logger-util');
const Users = db.users;
const Danmu = db.danmu;

// 创建弹幕
async function updateDanmuCount(model, queryField, updateField, type) {
    // 查询信息
    let fOneInfo = await model.findOne({ where:{ id: queryField } });
    let commentCount = parseInt(fOneInfo[updateField]);
    let updateParam = {
        [updateField]: type == 'add' ? commentCount + 1 : commentCount - 1
    };
    await model.update(updateParam, { where:{ id: fOneInfo.id} });
};
exports.create = (req, res) => {
    try {
        const createInfo = req.body;
        // 创建弹幕
        DAO.create(Danmu, createInfo, async data => {
            // 更新用户弹幕数
            await updateDanmuCount(Users, createInfo.userId, 'danmuCount', 'add');
            res.sendResult(data);
        })
    } catch (e) {
        console.log(e);
        logger.error(e);
        res.sendResultAto(null, 500, '服务器错误，请联系管理员！');
    }
};

// 查询弹幕列表
exports.findAll = async (req, res) => {
    const fAllInfo = req.body;
    let userAll = await Users.findAll();
    DAO.list(Danmu, fAllInfo, list => {
        let danmuAll = list.data.data;
        userAll.forEach(item => {
            danmuAll.forEach(subItem => {
                if(item.id === subItem.userId) {
                    subItem.avatar = item.avatar
                    subItem.nickname = item.nickname
                }
            })
        });
        res.sendResult(list);
    })
};

// 删除
exports.delete = (req, res) => {
    const deleteInfo = req.body;
    DAO.delete(Danmu, { id: deleteInfo.id}, async data => {
        await updateDanmuCount(Users, createInfo.userId, 'danmuCount', 'delete');
        res.sendResult(data);
    });
};

// 删除所有弹幕
exports.deleteAll = (req, res) => {
    DAO.deleteAll(Danmu, data => {
        res.sendResult(data)
    });
};
